#-----------------------------------------------------
# EII Light Lib
#-----------------------------------------------------
# Designed by Aixi Wang
#-----------------------------------------------------
# Example code to demostrate:
# * how to receive EII inferencing result from VI or VA
# * how to control EII VI
#
# Note: [1] no dependence with EII messagebus lib, so you can run any platform (Windows, Linux)
#
# The sample interface file:
'''
{
      "Servers": [
            {
                "Name": "default",
                "Type": "zmq_tcp",
                "EndPoint": "0.0.0.0:64013",
                "AllowedClients": [
                    "*"
                ]
            }
        ],
    "Publishers": [
        {
            "AllowedClients": [
                "*"
            ],
            "EndPoint": "0.0.0.0:65013",
            "Name": "default",
            "Topics": [
                "camera1_stream_results"
            ],
            "Type": "zmq_tcp"
        }
    ]
}
'''

#
import time
import os
import json
import zmq

# please change below information to match the real interfaces settings
zmq_addr1 = 'tcp://192.168.2.110:64013'
zmq_addr2 = 'tcp://192.168.2.110:65013'

#-------------------
# readfile
#-------------------
def readfile(filename):
    f = open(filename,'rb')
    fs = f.read()
    fs = fs.decode('utf-8')
    f.close()
    return fs

def writefile(filename,content):
    f = open(filename,'wb')
    if type(content) == str:
        content_bytes = content.encode('utf-8')
        f.write(content_bytes)
    else:
        f.write(content)
    f.close()
    return

#-------------------
# writefile2
#-------------------
def writefile2(filename,content):
    f = open(filename,'ab')
    if type(content) == str:
        content_bytes = content.encode('utf-8')
        f.write(content_bytes)
    else:
        f.write(content)
    f.flush()
    f.close()
    return
    
#-------------------
# has_file
#-------------------
def has_file(filename):
    if os.path.exists(filename):
        return True
    else:
        return False
        
#-------------------
# remove_file
#-------------------
def remove_file(filename):
    if os.path.exists(filename):
        os.remove(filename)

#-------------------
# get_file_size
#-------------------        
def get_file_size(fname):
    if has_file(fname):
        statinfo = os.stat(fname)
        return statinfo.st_size
    else:
        return 0

#-------------------
# load_config
#-------------------        
def load_config():
    try:
        s = readfile('config.json')
        config = json.loads(s)
        print('load config ok')
        return config
    except Exception as e:
        print('load config exception', str(e))
        return {}

#----------------------------------------------------------------------------------
# service_call
# test service: STOP_INGESTION
# cmd_msg: [b'default\x00', b'\x00', b'\x01', b'{"command":"STOP_INGESTION"}']
# resp: [b'default\x00', b'\x00', b'\x01', b'{"reply_payload":{"status_code":3}}']
# sleep 10 sec...
# test service: SNAPSHOT
# cmd_msg: [b'default\x00', b'\x00', b'\x01', b'{"command":"SNAPSHOT"}']
# resp: [b'default\x00', b'\x00', b'\x01', b'{"reply_payload":{"status_code":0}}']
# sleep 3 sec...
# test service: START_INGESTION
# cmd_msg: [b'default\x00', b'\x00', b'\x01', b'{"command":"START_INGESTION"}']
# resp: [b'default\x00', b'\x00', b'\x01', b'{"reply_payload":{"status_code":0}}']
#-----------------------------------------------------------------------------------
def service_call(zmq_addr,server_name,cmd_str):
    try:
        context = zmq.Context()
        service_client = context.socket(zmq.REQ)
        service_client.connect(zmq_addr1)
        cmd_msg = [('%s\x00' % (server_name)).encode('utf-8'),b'\x00',b'\x01',('{"command":"%s"}'%(cmd_str)).encode('utf-8') ]
        #print('cmd_msg:',cmd_msg)
        service_client.send_multipart(cmd_msg)
        resp = service_client.recv_multipart()
        del context
        return 0, resp[3].decode('utf-8')
    except Exception as e:
        return -1, 'exception:' + str(e)
        
#----------------------
# test_service
#----------------------
def test_service():
    print('test service interface...')
    print('-------------------------------')

    if 1:
        print('test service: STOP_INGESTION')
        resp = service_call(zmq_addr1,'default','STOP_INGESTION')
        print('resp:',resp)
        print('sleep 10 sec...')
        time.sleep(3)

    if 1:
        print('test service: SNAPSHOT')
        resp = service_call(zmq_addr1,'default','SNAPSHOT')
        print('resp:',resp)

        print('sleep 3 sec...')
        time.sleep(3)

    if 1:
        print('test service: SNAPSHOT')
        resp = service_call(zmq_addr1,'default','SNAPSHOT')
        print('resp:',resp)

        print('sleep 3 sec...')
        time.sleep(3)


    if 1:
        print('test service: SNAPSHOT')
        resp = service_call(zmq_addr1,'default','SNAPSHOT')
        print('resp:',resp)

        print('sleep 3 sec...')
        time.sleep(3)


    if 1:
        print('test service: SNAPSHOT')
        resp = service_call(zmq_addr1,'default','SNAPSHOT')
        print('resp:',resp)

        print('sleep 3 sec...')
        time.sleep(3)

    if 1:
        print('test service: START_INGESTION')    
        resp = service_call(zmq_addr1,'default','START_INGESTION')
        print('resp:',resp)
    

#-----------------
# test_sub
#-----------------
def eii_sub_thread():
    
    if has_file('img') == False:
        os.mkdir('img')
    print('test message sub function')
    print('-------------------------------')
    context2 = zmq.Context()
    va_receiver = context2.socket(zmq.SUB)
    va_receiver.setsockopt(zmq.SUBSCRIBE, b'')

    
    while True:
        try: 
            va_receiver.connect(zmq_addr2)
            while True:
                message = va_receiver.recv_multipart()
                print('len of message:',len(message))
                # message[0] topic : b'camera1_stream_results\x00'
                # message[1] b'\x00'
                # message[2] b'\x02'
                # message[3] metadata: b'{"frame_number":5309,"channels":3,"encoding_type":"jpeg","height":480,"img_handle":"121a95dd1a","width":640,"encoding_level":95}'
                # message[4] image payload, jpg file
                frame_number = json.loads(message[3].decode('utf-8'))['frame_number']
                img_filename = 'img/' + str(frame_number) + '.jpg'
                print('writing img file:',img_filename)
                writefile(img_filename,message[4])
                #print(message[4])
                
        except Exception as e:
            print('zmq_proxy exception:',str(e))
            time.sleep(1)

if __name__ == "__main__":

    #
    eii_sub_thread()
    #test_service()
    